package main

import (
	"github.com/kataras/iris"
	"runtime"
	"os"
	"flag"
	"fmt"
	"until"
	myapp "app"
	"app/middleware"
	"until/yml"
	"os/signal"
	"syscall"
	"time"
	"app/modules/rpc/grpcpool"
	"app/service"
	"until/logger"
	stdContext "context"
)

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU()*2)//初始化线程
}
func main() {
	dir, _ := os.Getwd()
	cmd_dir:= flag.String("dir", dir, "config dir")
	flag.Parse()
	fmt.Println("cmddir:",*cmd_dir)
	app := iris.New()
	app.Use(middleware.Before)
	until.Untilinit(*cmd_dir,app)
	myapp.Start(app)
	go graceful(app)
	//app.Run(iris.Addr(":"+yml.Config.AppPort),iris.WithoutInterruptHandler)
	app.Run(iris.Addr(":"+yml.Config.AppPort))
}
// 优雅关闭
func graceful(app *iris.Application) {
	ch := make(chan os.Signal, 1)
	signal.Notify(ch,
		os.Interrupt,
		syscall.SIGINT,
		os.Kill,
		syscall.SIGKILL,
		syscall.SIGTERM,
	)
	select {
	case <-ch:
		logger.Info("关闭中...")
		timeout := 5 * time.Second
		ctx, cancel := stdContext.WithTimeout(stdContext.Background(), timeout)
		defer cancel()
		app.Shutdown(ctx)
		shutdown()
	}
}
// 应用退出
func shutdown() {
	defer func() {
		logger.Info("已退出")
		os.Exit(0)
	}()

	//if !app.Installed {
	//	return
	//}
	logger.Info("应用准备退出")
	serviceTask := new(service.Task)
	// 停止所有任务调度
	logger.Info("停止定时任务调度")
	serviceTask.StopAll()

	taskNumInRunning := service.TaskNum.Num()
	logger.Infof("正在运行的任务有%d个", taskNumInRunning)
	if taskNumInRunning > 0 {
		logger.Info("等待所有任务执行完成后退出")
	}
	for {
		if taskNumInRunning <= 0 {
			break
		}
		time.Sleep(3 * time.Second)
		taskNumInRunning = service.TaskNum.Num()
	}

	// 释放gRPC连接池
	grpcpool.Pool.ReleaseAll()
}